﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using ExchangeClient.DbCache;
using ExchangeClient.DbCache.Model;
using ExchangeClient.ESB.Model;
using ExchangeClient.SAP;
using ExchangeClient.SAP.Model;
using ExchangeClient.Yidea;
using Google.Protobuf;
using HKH.Data;
using HKH.Mef2.Integration;
using MathNet.Numerics;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog.Fluent;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Quartz.Simpl;
using Quartz.Util;
using SyncService.Abstractions.Events;
using SyncService.Common;
using SyncService.Core.Model;
using SyncService.Core.Utils;
using SyncService.Model;
using SyncService.Results;
using SyncService.WebHost.Controllers;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Data;
using System.IO.Pipelines;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using AssetMaster = SyncService.Core.Model.AssetMaster;
using JsonSerializer = System.Text.Json.JsonSerializer;
using SAPAsset = SyncService.Model.SAPAsset;



namespace SyncService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class EsbController : MefControllerBase
    {
        private readonly ILogger<EsbController> _logger;
        private readonly IMemoryCache _cache;
        private UserDefines _setting;
        private ExtendFields _extendFields;
        private static readonly object _lock = new object();
        public EsbController(CompositionContainer mefContainer, ILogger<EsbController> logger, IMemoryCache cache, UserDefines setting, ExtendFields extendFields)
            : base(mefContainer)
        {
            _setting = setting;
            _extendFields = extendFields;
            _logger = logger;
            _cache = cache;
        }

        private bool ValidSecret()
        {
            var tokenStart = _extendFields.Where(e => e.Name == "ESBTokenStart" && e.ObjectType == 0).FirstOrDefault();
            var secret = _extendFields.Where(e => e.Name == "ESBToken" && e.ObjectType == 0).FirstOrDefault();

            bool result = false;
            if (tokenStart.FieldId == "0")
            {
                return true;
            }
            try
            {
                string authHeader = HttpContext.Request.Headers["token"];
                if (!string.IsNullOrEmpty(authHeader))
                {

                    if (secret.FieldId == authHeader)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return result;
        }

        /// <summary>
        /// 包装获取资产分类
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        [Route("GetAssetType")]
        public ActionResult GetAssetType()
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var result = yideaClient.GetAssetTypes(null).ToList();
            return Ok(new ApiResult(0, "", result));
        }
        /// <summary>
        /// sap推送公司主数据
        /// </summary>
        /// <param name="companyList"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DealCompany")]
        public ActionResult DealCompany([FromBody] List<CompanyCustomer> companyList)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            _logger.LogInformation("公司主数据：" + System.Text.Json.JsonSerializer.Serialize(companyList));
            if (companyList.Count == 0)
            {
                return Ok(new ApiResult(-1, "数据为空"));
            }
            var body = System.Text.Json.JsonSerializer.Serialize<List<CompanyCustomer>>(companyList);
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessExternalEvent(new RequestData("", "", "", body, "com" + Guid.NewGuid()), _cache);

            return Ok(new ApiResult(0, "", null));
        }
        /// <summary>
        /// sap推送成本中心
        /// </summary>
        /// <param name="centerList"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DealCenter")]
        public ActionResult DealCenter([FromBody] List<CenterData> centerList)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            _logger.LogInformation("成本中心数据：" + JsonSerializer.Serialize(centerList));

            if (centerList.Count == 0)
            {
                return Ok(new ApiResult(-1, "数据为空"));
            }
            var body = JsonSerializer.Serialize<List<CenterData>>(centerList);
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessExternalEvent(new RequestData("", "", "", body, "cen" + Guid.NewGuid()), _cache);

            return Ok(new ApiResult(0, "", null));
        }
        /// <summary>
        /// 包装给esb添加采购申请单
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("AddPurchaseApplication")]
        public object AddPurchaseApplication([FromBody] UserDefinedForm form)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            try
            {
                _logger.LogInformation("采购申请");
                _logger.LogInformation(form.Id.ToString());
                _logger.LogInformation(form.JsonData);
                form.JsonData = form.JsonData.Replace("--", " ");
                var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
                var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
                var result = yideaClient.AddNewUserDefinedForm(form);
                return Ok(new ApiResult(0, "success", result));
            }
            catch (Exception ex)
            {
                return Ok(new ApiResult(-1, ex.ToString()));
            }
        }
        /// <summary>
        /// 包装接口获取管理员
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetUsers")]
        public ActionResult GetUsers()
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var result = yideaClient.GetUsers(null).ToList();
            return Ok(new ApiResult(0, "", result));
        }

        [HttpPost]
        [Route("AddAsset")]
        public ActionResult AddAsset([FromBody] SAPAsset asset)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            lock (_lock)
            {
                //Thread.Sleep(10000);
                try
                {
                    _logger.LogInformation("开始新增");
                    var body = System.Text.Json.JsonSerializer.Serialize<SAPAsset>(asset);
                    _logger.LogInformation("AddAsset body:" + body);
                    var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
                    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;

                    var assetMasterTopTypeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "资产大类");
                    var assetMasterSourceField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "资产来源");
                    var isGuozhangField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");
                    var isDeferField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "是否递延");
                    var involvedCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
                    var financeCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "财务资产编码");
                    var companyCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                    var centerCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心代码");

                    var companyNameField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
                    var centerNameField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");

                    var zjdateField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "折旧开始日");
                    var useYearField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "使用年");
                    var useMonthField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "使用月");
                    var zjCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "折旧码");
                    var amountField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "资产原值");
                    var companyCode = _extendFields.First(x => x.Name == "CompanyCode");


                    QueryParam queryParam = new QueryParam();
                    queryParam.FilterString = "extensionFilters=[{label:\"" + financeCodeField.FieldId + "\",operator:\"EqualTo\",value:\"" + asset.FinanceCode + "\"},{label:\"" + companyCodeField.FieldId + "\",operator:\"EqualTo\",value:\"" + asset.CompanyCode + "\"}]";
                    var employee = yideaClient.GetEmployee(asset.ManagerEmployeeId, "");
                    if (employee == null)
                    {
                        return Ok(new ApiResult(-1, "员工不存在", null));
                    }
                    List<Asset> assets = yideaClient.GetAssets(queryParam).ToList();
                    if (assets.Count > 0)
                    {
                        var result1 = new
                        {
                            assetId = assets[0].Id.ToString(),
                            barcode = assets[0].Barcode.ToString()
                        };
                        return Ok(new ApiResult(0, "该编码已存在，不允许新增", result1));
                        //return Ok(new ApiResult(-1, "该编码已存在，不允许新增", null));
                    }
                    List<AssetType> assetTypeList = new List<AssetType>();
                    assetTypeList = yideaClient.GetAssetTypes(null).ToList();

                    var topAssetType = assetTypeList.Where(e => e.Code == asset.AssetTypeCode).FirstOrDefault();
                    if (topAssetType == null)
                    {
                        return Ok(new ApiResult(-1, "分类不存在"));
                    }
                    var secondType = assetTypeList.Where(e => e.ParentTypeCode == asset.AssetTypeCode && e.Name == "工程类").FirstOrDefault();
                    if (secondType == null)
                    {
                        return Ok(new ApiResult(-1, "二级分类不存在"));
                    }
                    var thirdType = assetTypeList.Where(e => e.ParentTypeCode == secondType.Code).FirstOrDefault();
                    if (thirdType == null)
                    {
                        return Ok(new ApiResult(-1, "末级分类不存在"));
                    }


                    var assetComapnyField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司名称"));
                    var assetCenterField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心名称"));

                    var companyMasterCodeField = _extendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
                    var companyMasterNameField = _extendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

                    var centerMasterCodeField = _extendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
                    var centerMasterNameField = _extendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");

                    var company = _setting.First(x => x.Name == "公司主数据");
                    var center = _setting.First(x => x.Name == "成本中心");
                    JsonObject companyDetail = new JsonObject();
                    var companyData = yideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
                    {
                        FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + asset.CompanyCode + "\"}]"
                    }).ToList();
                    string companyName = "";
                    if (companyData.Count > 0)
                    {
                        companyDetail = JsonNode.Parse(JsonSerializer.Serialize(companyData[0].Data)).AsObject();
                        JsonObject companyDataJson = JsonNode.Parse(companyData[0].Data["dataJson"].ToString()).AsObject();
                        companyDetail[companyMasterNameField.FieldId] = companyDataJson[companyMasterNameField.FieldId].ToString();
                        companyName = companyDataJson[companyMasterNameField.FieldId].ToString();
                        companyDetail.Remove("dataJson");
                        companyDetail[companyMasterCodeField.FieldId] = asset.CompanyCode;
                    }

                    JsonObject centerDetail = new JsonObject();
                    var centerData = yideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
                    {
                        FilterString = "[{\"field\":\"" + centerMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + asset.CenterCode + "\"}]"
                    }).ToList();
                    string centerName = "";
                    if (centerData.Count > 0)
                    {
                        centerDetail = JsonNode.Parse(JsonSerializer.Serialize(centerData[0].Data)).AsObject();
                        JsonObject centerDataJson = JsonNode.Parse(centerData[0].Data["dataJson"].ToString()).AsObject();
                        centerDetail[centerMasterNameField.FieldId] = centerDataJson[centerMasterNameField.FieldId].ToString();
                        centerName = centerDataJson[centerMasterNameField.FieldId].ToString();
                        centerDetail.Remove("dataJson");
                        centerDetail[centerMasterCodeField.FieldId] = asset.CenterCode;
                    }

                    Asset yideaAsset = new Asset();
                    yideaAsset.UseCompanyCode = companyCode.FieldId.ToString();
                    yideaAsset.OwnCompanyCode = companyCode.FieldId.ToString();
                    yideaAsset.Name = asset.Name;
                    yideaAsset.Specs = "";
                    yideaAsset.ManagerEmployeeId = employee.Id.ToString();
                    yideaAsset.PurchasedDate = asset.PurchasedDate.ToString();
                    yideaAsset.AssetTypeCode = thirdType.Code;
                    yideaAsset.DistrictCode = asset.DistrictCode;
                    yideaAsset.Source = 1;
                    yideaAsset.Amount = decimal.Parse(asset.Amount ?? "0");
                    yideaAsset.DataJson = "{\"" + centerNameField.FieldId + "\":\"" + centerName + "\",\"" + companyNameField.FieldId + "\":\"" + companyName + "\",\"" + financeCodeField.FieldId + "\":\"" + asset.FinanceCode + "\",\"" + assetMasterSourceField.FieldId + "\":{\"value\":\"工程长摊\",\"label\":\"工程长摊\",\"color\":{\"backgroundColor\":\"#4fbbe0\",\"foreColor\":\"#ffffff\"}},\"" + assetMasterTopTypeField.FieldId + "\":{\"value\":\"工程类长摊\",\"label\":\"工程类长摊\",\"color\":{\"backgroundColor\":\"#33d2b8\",\"foreColor\":\"#ffffff\"}},\"" + amountField.FieldId + "\":\"" + asset.Amount + "\",\"" + isGuozhangField.FieldId + "\":\"否\",\"" + involvedCodeField.FieldId + "\":\"1\",\"" + involvedCodeField.FieldId + "\":\"1\",\"" + assetComapnyField.FieldId + "\":" + companyDetail + ",\"" + assetCenterField.FieldId + "\":" + centerDetail + ",\"" + companyCodeField.FieldId + "\":\"" + asset.CompanyCode + "\",\"" + centerCodeField.FieldId + "\":\"" + asset.CenterCode + "\",\"" + zjdateField.FieldId + "\":\"" + asset.ZJDate + "\",\"" + useYearField.FieldId + "\":\"" + asset.UseYear + "\",\"" + useMonthField.FieldId + "\":\"" + asset.UseMonth + "\",\"" + zjCodeField.FieldId + "\":\"" + asset.ZJCode + "\",\"" + isDeferField.FieldId + "\":\"" + asset.IsDefer + "\"}";



                    var result = yideaClient.AddAsset(yideaAsset);
                    var data = new
                    {
                        assetId = result["assetId"].ToString(),
                        barcode = result["barcode"].ToString()
                    };
                    _logger.LogInformation("新增结束");
                    return Ok(new ApiResult(0, "", data));
                }
                catch (Exception ex)
                {
                    return Ok(new ApiResult(-1, ex.ToString()));
                }
            }
        }


        /// <summary>
        /// 心跳接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("HeartThrob")]
        public object HeartThrob()
        {
            try
            {
                IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
                var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;

                QueryParam queryParam = new QueryParam();
                queryParam.FilterString = "barcode=123456";

                var a = yideaClient.GetAssets(queryParam);

                return Ok(new
                {
                    code = 1,
                    msg = "success"
                });
            }
            catch (Exception ex)
            {
                return Ok(new
                {
                    code = 2,
                    msg = ex.ToString()
                });
                throw;
            }
        }

        /// <summary>
        /// 修改是否过账
        /// </summary>
        /// <param name="updateArgument"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateAssets")]
        public object UpdateAssets([FromBody] UpdateArgument updateArgument)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            lock (_lock)
            {
                try
                {
                    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
                    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;


                    Asset asset = yideaClient.GetAsset(updateArgument.AssetsCode);

                    if (updateArgument.IsCarryto == "true")
                    {
                        updateArgument.IsCarryto = "是";
                    }
                    else if (updateArgument.IsCarryto == "false")
                    {
                        updateArgument.IsCarryto = "否";
                    }
                    else if (updateArgument.IsCarryto == "1")
                    {
                        updateArgument.IsCarryto = "是";
                    }
                    else if (updateArgument.IsCarryto == "0")
                    {
                        updateArgument.IsCarryto = "否";
                    }

                    if (asset != null)
                    {
                        if (!string.IsNullOrEmpty(asset.PurchasedDate))
                        {
                            var purchasedDate = DateTime.Parse(asset.PurchasedDate);
                            asset.PurchasedDate = purchasedDate.AddHours(8).ToString();
                        }
                        var AssetFirst = asset.DataJson;
                        var isGuozhangField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");

                        // 解析 JSON
                        JObject jsonObject = JObject.Parse(AssetFirst);

                        // 获取指定索引的值
                        jsonObject[isGuozhangField.FieldId] = updateArgument.IsCarryto;


                        asset.DataJson = jsonObject.ToString();
                        var b = yideaClient.UpdateAsset(asset, asset);
                        if (b == true)
                        {
                            Console.WriteLine("修改成功。");
                        }
                        return Ok(new ApiResult(0, updateArgument.AssetsCode, updateArgument.IsCarryto));
                    }
                    else
                    {
                        updateArgument.AssetsCode = "编码不存在或错误";
                        updateArgument.IsCarryto = "修改失败";
                        return Ok(new ApiResult(-1, updateArgument.AssetsCode, updateArgument.IsCarryto));
                    }

                }
                catch (Exception ex)
                {
                    return Ok(new ApiResult(-1, ex.ToString()));
                    throw;
                }
            }
        }

        [HttpPost]
        [Route("GetAsset1234")]
        public object GetAsset1234(string lalalal)
        {
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var fromid = _setting.First(x => x.Name == "收货自定义表单");

            Asset asset = yideaClient.GetAsset(lalalal);

            if (asset != null)
            {
                if (!string.IsNullOrEmpty(asset.PurchasedDate))
                {
                    var purchasedDate = DateTime.Parse(asset.PurchasedDate);
                    asset.PurchasedDate = purchasedDate.AddHours(8).ToString();
                }
                var AssetFirst = asset.DataJson;
                var isGuozhangField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "是否递延");

                // 解析 JSON
                JObject jsonObject = JObject.Parse(AssetFirst);

                // 获取指定索引的值
                jsonObject[isGuozhangField.FieldId] = "是";


                asset.DataJson = jsonObject.ToString();
                var b = yideaClient.UpdateAsset(asset, asset);
                if (b == true)
                {
                    Console.WriteLine("修改成功。");
                }
                return Ok(1);
            }
            else
            {
            }

            return 1;
        }

        /// <summary>
        /// esb推送审批单据状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UpdateBillStatus")]
        public object UpdateBillStatus([FromBody] UpdateBillModel model)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            if (model == null)
            {
                return Ok(new ApiResult(-1, "数据为空"));
            }
            var body = JsonSerializer.Serialize<UpdateBillModel>(model);
            _logger.LogInformation("UpdateBillStatus body:" + body);
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessExternalEvent(new RequestData("", "", "", body, "upd" + model.billNo + model.procInstId + model.status), _cache);

            return new
            {
                code = "000000",
                message = "操作成功"
            };
        }

        [HttpPost]
        [Route("GetBillData")]
        public IActionResult GetBillData([FromBody] BillData data)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var form = _setting.First(x => x.Name == "单据状态记录");
            List<UserDefinedForm> userdefinedList = yideaClient.GetUserDefinedForms(form.Id, new QueryParam() { FilterString = "[{\"field\":\"createdTime\",\"type\":\"date\",\"label\":\"提交时间\",\"opt\":\"Between\",\"val\":[\"" + data.BeginDate + "\",\"" + data.EndDate + "\"],\"format\":\"yyyy-MM-dd HH:mm:ss\"}]" }).ToList();
            List<BillResponse> responses = new List<BillResponse>();
            var billnoField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "billno");
            var procInstIdField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "procInstId");
            var stateField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "state");
            foreach (var userdefined in userdefinedList)
            {
                var jsonData = userdefined!.JsonDataObject!;
                var billno = jsonData[billnoField.FieldId]!.ToString();
                var procInstId = jsonData[procInstIdField.FieldId]!.ToString();
                var state = int.Parse(jsonData[stateField.FieldId].ToString());
                responses.Add(new BillResponse()
                {
                    BillNo = billno,
                    ProcInstId = procInstId,
                    Status = state
                });
            }
            List<UserDefinedForm> userdefinedList1 = yideaClient.GetUserDefinedForms(form.Id, new QueryParam() { FilterString = "[{\"field\":\"modifiedTime\",\"type\":\"date\",\"label\":\"更新时间\",\"opt\":\"Between\",\"val\":[\"" + data.BeginDate + "\",\"" + data.EndDate + "\"],\"format\":\"yyyy-MM-dd HH:mm:ss\"}]" }).ToList();

            foreach (var userdefined1 in userdefinedList)
            {
                var jsonData = userdefined1!.JsonDataObject!;

                var billno = jsonData[billnoField.FieldId]!.ToString();
                var procInstId = jsonData[procInstIdField.FieldId]!.ToString();
                var state = int.Parse(jsonData[stateField.FieldId].ToString());
                var item = responses.Where(e => e.BillNo == billno).ToList();
                if (item.Count == 0)
                {
                    responses.Add(new BillResponse()
                    {
                        BillNo = billno,
                        ProcInstId = procInstId,
                        Status = state
                    });
                }
            }
            responses = responses.Select(e => e).Distinct().ToList();

            return Ok(new { code = 000000, message = "success", result = responses });
        }

        private async Task<string> GetBody()
        {
            var payload = string.Empty;
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                await Request.Body.CopyToAsync(stream);
                stream.Seek(0, SeekOrigin.Begin);
                payload = await reader.ReadToEndAsync();
            }
            return payload;
        }
        /// <summary>
        /// 接收易点自定义表单数据推送
        /// </summary>
        /// <param name="nonce"></param>
        /// <param name="timestamp"></param>
        /// <param name="signature"></param>
        /// <param name="deliverId">报文推送中间程序唯一字段</param>
        /// <param name="isDebug"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Push")]
        public async Task<object> Push([FromQuery] string nonce,
            [FromQuery] string timestamp, [FromHeader(Name = "X-YIDEA-Signature")] string signature,
            [FromHeader(Name = "X-YIDEA-DeliverId")] string deliverId, [FromQuery] bool? isDebug)
        {

            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var mysqlClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == "mysqlcache").Value;
            if (string.IsNullOrEmpty(deliverId))
            {
                return ApiResult.Success;
            }


            var fanhui = mysqlClient.GetData(new JsonObject { ["Flag"] = 4, ["deliverId"] = deliverId });
            if (fanhui["consequenceconsequence"]?.GetValue<int>() > 0)
            {
                _logger.LogDebug($"请求正在处理，忽略此重复请求：DeliverId={deliverId}, TimeStamp={timestamp}");
                return ApiResult.Success;
            }




            _logger.LogInformation("pushBody:开始");
            string body = await GetBody();
            _logger.LogInformation("pushBody:" + body);
            var sadsadsa = JsonObject.Parse(body);
            var json1 = sadsadsa["op"].ToString();
            var json2 = sadsadsa["data"].ToString();
            var datajson2 = JObject.Parse(json2);
            var FormName = datajson2["FormName"].ToString();
            var SerialNo = "";
            JToken barcodeToken;
            JToken serialNoToken;
            // 尝试获取 Barcode 字段
            bool hasBarcode = datajson2.TryGetValue("Barcode", out barcodeToken) && !string.IsNullOrEmpty(barcodeToken.ToString());
            // 尝试获取 SerialNo 字段
            bool hasSerialNo = datajson2.TryGetValue("SerialNo", out serialNoToken) && !string.IsNullOrEmpty(serialNoToken.ToString());
            if (hasBarcode)
            {
                SerialNo = barcodeToken.ToString();
            }
            else if (hasSerialNo)
            {
                SerialNo = serialNoToken.ToString();
            }
            else
            {
                // 可根据实际需求调整，比如记日志、返回错误等
                _logger.LogError("Barcode 和 SerialNo 字段在报文中均未有效存在，无法设置 SerialNo");
                // 这里也可以抛异常让上层处理，或者给个默认标识
                SerialNo = "未知编号";
            }

            var FromName = datajson2["FromName"]?.ToString();
            var time = DateTime.Now.ToString("yyyyMMddhhmmss");


            if (!string.IsNullOrEmpty(body))
            {
                mysqlClient.GetData(new JsonObject { ["Flag"] = 6, ["deliverId"] = deliverId, ["BarCode"] = SerialNo, ["DataJson"] = body, ["PushSate"] = json1, ["FromNmae"] = FormName, ["Dateime"] = time });
            }


            if (string.IsNullOrEmpty(body))
            {
                return Ok();
            }
            bool flag = false;
            if (isDebug.HasValue && isDebug.Value)
            {
                flag = true;
            }
            else
            {
                flag = Validate(body, nonce, timestamp, signature);
            }

            if (flag)
            {
                var eventHub = MefContainer.GetExport<IEventHub>();
                eventHub.ProcessYideaEvent(new RequestData(nonce ?? "", signature ?? "", timestamp ?? "", body.ToString(), deliverId ?? ""), _cache);
                var syncEvent = AssetSyncEvent.Parse($"{nonce}|{timestamp}", body);
                var serialno = syncEvent.Data["SerialNo"] == null ? (syncEvent.Data["Barcode"] == null ? "" : syncEvent.Data["Barcode"].ToString()) : syncEvent.Data["SerialNo"].ToString();
                return Ok(new { message = "op:" + syncEvent.EventType + " type:" + syncEvent.SourceType + " seriaNo:" + serialno });
            }
            else
            {
                return Unauthorized(new { message = "fail" });
            }
        }
        [HttpPost]
        [Route("PushInventory")]
        public async Task<object> PushInventory()
        {
            string body = await GetBody();
            if (string.IsNullOrEmpty(body))
            {
                return Ok();
            }
            var data = JsonObject.Parse(body);
            if (data["op"].ToString() == "create")
            {
                return Ok();
            }
            _logger.LogInformation("PushInventorybody" + body.ToString());
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessYideaEvent(new RequestData("", "", "", body.ToString(), ""), _cache);
            return Ok();
        }


        /// <summary>
        /// sap向固资系统同步资产
        /// </summary>
        /// <param name="assetMasters"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("DealAssetMasterData")]
        public IActionResult DealAssetMasterData([FromBody] List<AssetMaster> assetMasters)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            _logger.LogInformation("DealAssetMasterData");
            if (assetMasters.Count == 0)
            {
                return Ok(new ApiResult(-1, "数据为空"));
            }
            var body = JsonSerializer.Serialize<List<AssetMaster>>(assetMasters);
            _logger.LogInformation("DealAssetMasterData body:" + body);
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessExternalEvent(new RequestData("", "Assets", "", body, Guid.NewGuid().ToString()), _cache);

            return Ok(new ApiResult(0, "", null));
        }
        [HttpPost]
        [Route("Receive")]
        public async Task<object> Receive([FromBody] List<ReceiveModel> ReceivBody)
        {
            if (!ValidSecret())
            {
                return await Task.FromResult(Ok(new ApiResult(-1, "Unauthorized", null)));
                //return Ok(new ApiResult(-1, "Unauthorized"));
            }
            _logger.LogInformation("Receive");
            if (ReceivBody.Count == 0)
            {
                return Ok(new ApiResult(-1, "数据为空"));
            }
            var body = JsonSerializer.Serialize<List<ReceiveModel>>(ReceivBody);
            _logger.LogInformation("Receive body:" + body);
            var eventHub = MefContainer.GetExport<IEventHub>();
            return await Task.FromResult(Ok(new ApiResult(0, "", null)));
        }

        /// <summary>
        /// SAP回调接口
        /// </summary>
        /// <param name="ReceivBody"></param>
        /// <returns></returns>
        [HttpPost("ReceiveData")]
        public async Task<IActionResult> ReceiveData([FromBody] ReceiveModel ReceivBody)
        {
            if (!ValidSecret())
            {
                return Ok(new ApiResult(-1, "Unauthorized"));
            }
            _logger.LogInformation("ReceiveData");
            if (ReceivBody == null)
            {
                return await Task.FromResult(Ok(new ApiResult(-1, "数据为空")));
            }
            try
            {
                JsonObject RestJsObject = new JsonObject();
                string SerialNo = string.Empty;
                var resultArray = ReceivBody.Result.Select(item => new JsonObject
                {
                    ["ZDJBH"] = item.zdjbh,
                    ["ZDJBH_IT"] = item.zdjbh_it,
                    ["ANLN1_X"] = item.anln1_x,
                    ["BUKRS_X"] = item.bukrs_x,
                    ["BarCode"] = item.barCode,
                    ["TYPE"] = item.type,
                    ["MESSAGE"] = item.message
                }).ToList();
                _logger.LogInformation("ReceiveData :" + JsonSerializer.Serialize(ReceivBody));
                _logger.LogInformation("ReceiveData body:" + JsonSerializer.Serialize(ReceivBody));
                SerialNo = resultArray?[0]?["ZDJBH"]?.ToString();
                if (!string.IsNullOrWhiteSpace(SerialNo))
                {
                    if (SerialNo.StartsWith("LAM"))
                    {
                        SerialNo = SerialNo.Substring(3);
                    }
                    RestJsObject.Add("SerialNo", SerialNo);
                }
                else
                {
                    return Unauthorized(new { message = "单据编号不可为空  errormessage result[0][ZDJBH]" });
                }
                var resultJsonArray = new JsonArray(resultArray.ToArray());
                RestJsObject.Add("baseInfo", JsonNode.Parse(JsonSerializer.Serialize(ReceivBody.BaseInfo)).AsObject());
                RestJsObject.Add("result", resultJsonArray);

                string body = JsonSerializer.Serialize(RestJsObject);

                var eventHub = MefContainer.GetExport<IEventHub>();

                eventHub.ProcessExternalEvent(new RequestData("", "Async", "", body, Guid.NewGuid().ToString()), _cache);

                return Ok(new ApiResult(200, "success", null));
            }
            catch (System.Text.Json.JsonException ex)
            {
                _logger.LogError(ex, "Error parsing JSON data");
                return Ok(new ApiResult(-1, "数据格式错误"));
            }
        }


        #region 退库单和领用单 
        //[HttpPost]
        //[Route("asdsadasd")]
        //public IActionResult asdsadasd(string asdsadas)
        //{
        //    var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
        //    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
        //    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
        //    var condition = new JsonArray();
        //    condition.Add(new JsonObject()
        //    {
        //        ["field"] = "serialNo",
        //        ["type"] = "input",
        //        ["label"] = "流水号",
        //        ["opt"] = "Equal",
        //        ["val"] = asdsadas
        //    });
        //    CustomizedFormData order = yideaClient.GetCustomizedFormDatas(VformId.Id, new QueryParam() { FilterString = JsonSerializer.Serialize(condition) }).FirstOrDefault();

        //    var datajson = JsonNode.Parse(order.Data["dataJson"].ToString());
        //    var assetList = datajson["table_1690536110546"].AsArray();
        //    var TuiKu = GenerateRefund(assetList, order, "公司内调拨");
        //    var LingYong = GenerateReceive(assetList, order, "公司内调拨");
        //    if (TuiKu)
        //    {
        //        return Ok("1");
        //    }
        //    return Ok("0");
        //}
        //private bool GenerateRefund(JsonArray assetList, CustomizedFormData order, string TransferType)
        //{
        //    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
        //    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
        //    #region 字段
        //    //新调拨单自定义字段
        //    var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
        //    var TuiKuField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "退库后实际存放地");
        //    var assetTableField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
        //    var assetBarcodeField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
        //    var assetAllotField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
        //    var assetSAPField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
        //    var assetQueryField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
        //    var CunFangDiField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
        //    var QuBuField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
        //    var UserField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");

        //    var assetVTestTableField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
        //    var assetVTestBarcodeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
        //    var assetVTestAllotField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
        //    var VTestTransferTypeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
        //    var assetVTestQueryField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
        //    var VTestCunFangDiField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
        //    var VTestQuBuField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
        //    var VTestUserField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");
        //    #endregion

        //    var btime = "";
        //    Order OrderJson = new Order();
        //    JsonArray assetTui = new JsonArray();
        //    btime = order.Data["modifiedTime"].ToString();

        //    var addressdate = "";
        //    var districtCodedate = "";
        //    bool qwe = false;

        //    JsonArray CunFang = new JsonArray();

        //    foreach (var item in assetList)
        //    {
        //        if (TransferType == "公司内调拨" && item[CunFangDiField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
        //        {
        //            CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[CunFangDiField2.FieldId]!.ToString() }));
        //        }
        //        else if (TransferType == "公司间调拨" && item[VTestCunFangDiField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
        //        {
        //            CunFang.Add(JsonSerializer.Serialize(new { CunFang = item[VTestCunFangDiField.FieldId]!.ToString() }));
        //        }
        //    }

        //    var deserializedArray = CunFang.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
        //    // 使用Distinct方法去重，基于name属性定义去重规则
        //    var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["CunFang"].ToString()).ToList();
        //    // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
        //    var resultArray = uniqueArray.Select(token => token).ToArray();
        //    var asd = "";
        //    foreach (var itemqwe in resultArray)
        //    {
        //        foreach (var item in assetList)
        //        {
        //            var a = "";
        //            if (TransferType == "公司内调拨" && item[assetAllotField2.FieldId].ToString() == "调拨成功")
        //            {
        //                a = item[CunFangDiField2.FieldId]!.ToString();

        //                asd = CunFangDiField2.FieldId;

        //                var b = itemqwe["CunFang"]!.ToString();
        //                if (a == b)
        //                {
        //                    var assetfrist = yideaClient.GetAsset(item[assetBarcodeField2.FieldId].ToString());
        //                    var asdsads = assetfrist.ManagerEmployeeName;
        //                    var sadwerq = assetfrist.ManagerEmployeeName;
        //                    var sate = assetfrist.State;
        //                    var user = assetfrist.User;
        //                    if (sate == 1 && user != null)
        //                    {
        //                        addressdate = item[CunFangDiField2.FieldId]!.ToString();
        //                        districtCodedate = item[QuBuField2.FieldId]["label"]!.ToString();

        //                        JsonObject assetdatajson = new JsonObject();
        //                        assetdatajson.Add("barcode", item["barcode"]!.ToString());
        //                        assetTui.Add(assetdatajson);
        //                    }
        //                }
        //            }
        //            else if (TransferType == "公司间调拨" && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
        //            {
        //                a = item[VTestCunFangDiField.FieldId]!.ToString();

        //                asd = VTestCunFangDiField.FieldId;

        //                var b = itemqwe["CunFang"]!.ToString();
        //                if (a == b)
        //                {
        //                    var assetfrist = yideaClient.GetAsset(item[assetVTestBarcodeField.FieldId].ToString());
        //                    var asdsads = assetfrist.ManagerEmployeeName;
        //                    var sadwerq = assetfrist.ManagerEmployeeName;
        //                    var sate = assetfrist.State;
        //                    var user = assetfrist.User;
        //                    if (sate == 1 && user != null)
        //                    {
        //                        addressdate = item[VTestCunFangDiField.FieldId]!.ToString();
        //                        districtCodedate = item[VTestQuBuField.FieldId]["label"]!.ToString();

        //                        JsonObject assetdatajson = new JsonObject();
        //                        assetdatajson.Add("barcode", item["barcode"]!.ToString());
        //                        assetTui.Add(assetdatajson);
        //                    }
        //                }
        //            }
        //        }

        //        JsonObject aasdTui = new JsonObject();
        //        aasdTui.Add("address", itemqwe["CunFang"]!.ToString());
        //        aasdTui.Add("districtCode", districtCodedate);
        //        aasdTui.Add("revertComment", "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成");
        //        aasdTui.Add("assets", assetTui);
        //        aasdTui.Add("actualRevertDate", btime);
        //        aasdTui.Add("companyCode", "01");
        //        aasdTui.Add("OwnerCompanyCode", "01");
        //        OrderJson.ExtraData = aasdTui;
        //        JsonObject dataJson = new JsonObject();
        //        dataJson.Add(TuiKuField.FieldId, itemqwe["CunFang"]!.ToString());
        //        var sdsadas = JsonSerializer.Serialize(dataJson);
        //        //退库单
        //        if (assetTui.Count == 0)
        //        {
        //            qwe = false;
        //            assetTui.Clear();
        //            aasdTui.Clear();
        //            dataJson.Clear();
        //        }
        //        else
        //        {
        //            qwe = yideaClient.UpdateAdminRefundAsset(OrderJson, null, sdsadas);
        //            if (qwe)
        //            {
        //                _logger.LogInformation("退库单生成成功");
        //                assetTui.Clear();
        //                aasdTui.Clear();
        //                dataJson.Clear();
        //            }
        //            else
        //            {
        //                qwe = false;
        //                assetTui.Clear();
        //                aasdTui.Clear();
        //                dataJson.Clear();
        //            }
        //        }
        //    }
        //    return qwe;
        //}
        ///// <summary>
        ///// 生成领用单
        ///// </summary>
        ///// <returns></returns>
        //private bool GenerateReceive(JsonArray assetList, CustomizedFormData order, string TransferType)
        //{
        //    IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
        //    var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
        //    #region 字段
        //    //新调拨单自定义字段
        //    var VformId = _setting.First(x => x.Name == "V测试资产调拨单");
        //    var lingCunField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "领用后实际存放地");
        //    var assetTableField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表");
        //    var assetBarcodeField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产编码");
        //    var assetAllotField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调拨状态");
        //    var assetSAPField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "sap单据状态");
        //    var assetQueryField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "资产列表query");
        //    var CunFangDiField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "实际存放地");
        //    var QuBuField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入区部");
        //    var UserField2 = _extendFields.First(x => x.ObjectType == 60 && x.Name == "调入使用人");

        //    var assetVTestTableField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表");
        //    var assetVTestBarcodeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产编码");
        //    var assetVTestAllotField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试公司间调拨状态");
        //    var VTestTransferTypeField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调拨类型");
        //    var assetVTestQueryField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试资产列表query");
        //    var VTestCunFangDiField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试实际存放地");
        //    var VTestQuBuField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入区部");
        //    var VTestUserField = _extendFields.First(x => x.ObjectType == 60 && x.Name == "V测试调入使用人");
        //    #endregion
        //    var btime = "";
        //    Order OrderJson = new Order();
        //    JsonArray assetTui = new JsonArray();
        //    JsonArray assetLing = new JsonArray();
        //    JsonArray name = new JsonArray();
        //    btime = order.Data["modifiedTime"].ToString();

        //    foreach (var item in assetList)
        //    {
        //        if (TransferType == "公司内调拨" && item[UserField2.FieldId] != null && item[assetAllotField2.FieldId].ToString() == "调拨成功")
        //        {
        //            name.Add(JsonSerializer.Serialize(new { name = item[UserField2.FieldId]!["label"]!.ToString() + item[CunFangDiField2.FieldId]!.ToString() }));
        //        }
        //        else if (TransferType == "公司间调拨" && item[VTestUserField.FieldId] != null && item[assetVTestAllotField.FieldId].ToString() == "调拨成功")
        //        {
        //            name.Add(JsonSerializer.Serialize(new { name = item[VTestUserField.FieldId]!["label"]!.ToString() + item[VTestCunFangDiField.FieldId]!.ToString() }));
        //        }
        //    }
        //    var deserializedArray = name.Select(token => JsonSerializer.Deserialize<JsonObject>(token.ToString())).ToList();
        //    // 使用Distinct方法去重，基于name属性定义去重规则
        //    var uniqueArray = deserializedArray.DistinctBy(jobject => jobject["name"].ToString()).ToList();
        //    // 将去重后的JObject列表重新序列化为JSON格式的JToken类型并放入新的JsonArray
        //    var resultArray = uniqueArray.Select(token => token).ToArray();
        //    bool ab = false;

        //    foreach (var item in resultArray)
        //    {
        //        var cunfang = "";
        //        var user = "";
        //        var districtCode = "";
        //        var c = "";
        //        foreach (var itemasset in assetList)
        //        {
        //            var a = "";
        //            if (TransferType == "公司内调拨" && itemasset[UserField2.FieldId] != null && itemasset[assetAllotField2.FieldId].ToString() == "调拨成功")
        //            {
        //                a = itemasset[UserField2.FieldId]["label"]!.ToString() + itemasset[CunFangDiField2.FieldId]!.ToString();

        //                var b = item["name"]!.ToString();
        //                if (a == b)
        //                {
        //                    c = itemasset[CunFangDiField2.FieldId]!.ToString();
        //                    JsonObject assetdatajsonling = new JsonObject();
        //                    districtCode = itemasset[QuBuField2.FieldId]["value"]!.ToString();
        //                    assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());
        //                    user = itemasset[UserField2.FieldId]["value"]!.ToString();
        //                    assetLing.Add(assetdatajsonling);
        //                }
        //            }
        //            else if (TransferType == "公司间调拨" && itemasset[VTestUserField.FieldId] != null && itemasset[assetVTestAllotField.FieldId].ToString() == "调拨成功")
        //            {
        //                a = itemasset[VTestUserField.FieldId]["label"]!.ToString() + itemasset[VTestCunFangDiField.FieldId]!.ToString();

        //                var b = item["name"]!.ToString();
        //                if (a == b)
        //                {
        //                    c = itemasset[VTestCunFangDiField.FieldId]!.ToString();
        //                    JsonObject assetdatajsonling = new JsonObject();
        //                    districtCode = itemasset[VTestQuBuField.FieldId]["value"]!.ToString();
        //                    assetdatajsonling.Add("barcode", itemasset["barcode"]!.ToString());
        //                    user = itemasset[VTestUserField.FieldId]["value"]!.ToString();
        //                    assetLing.Add(assetdatajsonling);
        //                    cunfang = itemasset[VTestCunFangDiField.FieldId].ToString();
        //                }
        //            }
        //        }
        //        JsonObject aasdLing = new JsonObject();
        //        aasdLing.Add("userEmployeeNo", user);
        //        aasdLing.Add("receiver", user);
        //        aasdLing.Add("address", c);
        //        aasdLing.Add("districtCode", districtCode);
        //        aasdLing.Add("departmentCode", "");
        //        aasdLing.Add("comment", "本单由调拨单号（" + order.Data["SerialNo"] + "）自动生成");
        //        aasdLing.Add("assets", assetLing);
        //        aasdLing.Add("operatedDate", btime);
        //        aasdLing.Add("companyCode", "01");
        //        OrderJson.ExtraData = aasdLing;
        //        JsonObject dataJson = new JsonObject();
        //        dataJson.Add(lingCunField.FieldId, c);
        //        var sdsadas = JsonSerializer.Serialize(dataJson);
        //        if (name.Count == 0)
        //        {
        //            assetLing.Clear();
        //            aasdLing.Clear();
        //            dataJson.Clear();
        //        }
        //        else
        //        {
        //            ab = yideaClient.UpdateAdminReceiveAsset(OrderJson, null, sdsadas);

        //            _logger.LogInformation("领用单生成成功");
        //            assetLing.Clear();
        //            aasdLing.Clear();
        //            dataJson.Clear();
        //            if (ab == false)
        //            {
        //                assetLing.Clear();
        //                aasdLing.Clear();
        //                dataJson.Clear();
        //            }
        //        }
        //    }
        //    return ab;
        //}

        #endregion


        [HttpPost]
        [Route("PushEsb2")]
        public object PushEsb2(string body)
        {
            //采购收单单推送
            //var body = "{\"op\":\"Create\",\"source\":{\"Type\":48,\"Id\":null},\"meta\":{\"audit\":\"7f060528-d92e-42d2-a640-37f87c887399\",\"batch\":\"1334fdc5-820d-4d2d-837a-81499b397875\"},\"data\":{\"FormId\":\"00791f91-81c8-4111-854d-081d8a3f90c1\",\"FormName\":\"采购收货\",\"FormType\":500,\"Operation\":0,\"OperatedTime\":\"2023-09-13 10:34:14\",\"Id\":\"768b79a0-5872-4980-860a-48154e166d80\",\"EnterpriseId\":0,\"DefinitionId\":\"3b66aa15-7488-49c5-a065-675dfffea629\",\"SerialNo\":\"REC202309130017\",\"CreatedBy\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"CreatedTime\":\"2023-09-13 10:34:14\",\"ModifiedBy\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"ModifiedTime\":\"2023-09-13 10:34:14\",\"ProcessInstanceId\":null,\"Status\":2,\"IsDelete\":0,\"SubmitedBy\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"SubmitedTime\":\"2023-09-13 10:34:14\",\"createdTime\":\"\",\"createdBy\":\"\",\"modifiedTime\":\"\",\"query_1690364378175\":{\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"金磊\",\"createdByNo\":\"208000025\",\"createdByTripartiteNo\":\"ou_8872fe2ebdf3cdf57e4dc4e90d237d3b\",\"submitedByNo\":\"208000025\",\"submitedByName\":\"金磊\",\"modifiedByName\":\"金磊\",\"id\":\"34d9e6d4-2741-430f-8dbd-ea4ecb5558cf\",\"formId\":\"08b421ec-6814-4dce-a9cc-1c9c7c3e9cc7\",\"definitionId\":\"a3cfcd03-b5b2-48c9-9e42-40ba68ca027d\",\"serialNo\":\"PO202309130017\",\"createdBy\":{\"value\":\"208000025\",\"label\":\"金磊\",\"code\":\"208000025\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"modifiedBy\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"modifiedTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"input_1692352091088\":\"浙江行政资产采购测试-x\",\"input_1693471062699\":\"CNY\",\"districtSelect_1692339920636\":{\"value\":\"2014\",\"label\":\"浙江区部\"},\"query_1689575494919\":{\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"Simon.li 李伟\",\"createdByNo\":\"202106485\",\"createdByTripartiteNo\":\"ou_14fdad93b7caab808559ad4c92a2f128\",\"submitedByNo\":\"202106485\",\"submitedByName\":\"Simon.li 李伟\",\"id\":\"326d253f-c28b-4bb5-a54b-b407fbe71f42\",\"formId\":\"dd548bb2-9cf2-478c-8b7f-828c1492ba7b\",\"definitionId\":\"138dbc3b-e092-44e4-b44c-ddd0c0a095c1\",\"serialNo\":\"PR202309130025\",\"createdBy\":{\"value\":\"202106485\",\"label\":\"Simon.li 李伟\",\"code\":\"202106485\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"E7740D86-3F64-4D65-8344-E2693C0FA8EB\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"input_1689556934951\":\"002\",\"input_1689556940115\":\"31Q0\",\"input_1689556940761\":\"浙江胜道体育用品有限公司\",\"input_1689556941164\":\"31Q0P51000\",\"input_1689556941526\":\"浙江人资行政部\",\"input_1689556941824\":\"SPQ40038\",\"input_1689556942153\":\"上海复御信息科技有限公司\",\"input_1689725618789\":\"LC17\",\"input_1689725620118\":\"白板\",\"input_1693388113761\":\"宜家\",\"input_1693388116253\":\"双面白板\",\"input_1689556942672\":\"白板\",\"number_1689557109961\":\"1\",\"number_1689557128622\":\"300.00\",\"number_1689557130034\":\"300.00\",\"textarea_1689557155464\":\"行政资产测试\",\"number_1689557268505\":\"1\",\"number_1689557269101\":\"300.00\",\"number_1689557269509\":\"1\",\"number_1689557270210\":\"300.00\",\"input_1693038392515\":\"FKPR202309130019\",\"input_1689725521319\":\"208000025\",\"input_1689725515608\":\"金磊\",\"date_1689556928024\":\"2023-09-13 00:00:00\",\"input_1689556933730\":\"CC1431Q02309130004\",\"districtSelect_1694154027560\":{\"label\":\"浙江区部\",\"value\":\"2014\"},\"input_1693470109280\":\"CNY\",\"uniqueId\":\"PR202309130025\"},\"input_1689575480136\":\"SPQ40038\",\"input_1689575527105\":\"上海复御信息科技有限公司\",\"date_1690361596575\":\"2023-09-13 00:00:00\",\"input_1692352137841\":\"未收货\",\"table_1690361666668\":[{\"query_1690361668382\":{\"id\":\"2dc98804-1888-436e-b173-06facd187e28\",\"serialNo\":\"PR202309130024\"},\"input_1693879193124\":\"GC01\",\"number_1693823979406\":\"1\",\"number_1693823982367\":\"1000.00\",\"number_1690362163665\":\"1\",\"number_1690362155400\":\"1000.00\",\"number_1690362159095\":\"1000.00\",\"number_1692612429157\":null,\"input_1693471244252\":\"31Q0\",\"input_1693471238680\":\"浙江胜道体育用品有限公司\",\"input_1693471241617\":\"31Q0P51000\",\"input_1693471235835\":\"浙江人资行政部\",\"subId\":\"e6b2b497-a726-49e7-8e8d-4e538750dfe8\",\"subIndex\":1,\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"Simon.li 李伟\",\"createdByNo\":\"202106485\",\"createdByTripartiteNo\":\"ou_14fdad93b7caab808559ad4c92a2f128\",\"submitedByNo\":\"202106485\",\"submitedByName\":\"Simon.li 李伟\",\"id\":\"2dc98804-1888-436e-b173-06facd187e28\",\"formId\":\"dd548bb2-9cf2-478c-8b7f-828c1492ba7b\",\"definitionId\":\"138dbc3b-e092-44e4-b44c-ddd0c0a095c1\",\"serialNo\":\"PR202309130024\",\"createdBy\":{\"value\":\"202106485\",\"label\":\"Simon.li 李伟\",\"code\":\"202106485\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"E7740D86-3F64-4D65-8344-E2693C0FA8EB\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"input_1689556934951\":\"001\",\"input_1689556940115\":\"31Q0\",\"input_1689556940761\":\"浙江胜道体育用品有限公司\",\"input_1689556941164\":\"31Q0P51000\",\"input_1689556941526\":\"浙江人资行政部\",\"input_1689556941824\":\"SPQ40038\",\"input_1689556942153\":\"上海复御信息科技有限公司\",\"input_1689725618789\":\"GC01\",\"input_1689725620118\":\"办公桌\",\"input_1693388113761\":\"11\",\"input_1693388116253\":\"双人桌\",\"input_1689556942672\":\"办公桌\",\"number_1689557109961\":\"1\",\"number_1689557128622\":\"1000.00\",\"number_1689557130034\":\"1000.00\",\"textarea_1689557155464\":\"行政资产测试\",\"number_1689557268505\":\"1\",\"number_1689557269101\":\"1000.00\",\"number_1689557269509\":\"1\",\"number_1689557270210\":\"1000.00\",\"input_1693038392515\":\"FKPR202309130019\",\"input_1689725521319\":\"208000025\",\"input_1689725515608\":\"金磊\",\"date_1689556928024\":\"2023-09-13 00:00:00\",\"input_1689556933730\":\"CC1431Q02309130004\",\"districtSelect_1694154027560\":{\"label\":\"浙江区部\",\"value\":\"2014\"},\"input_1693470109280\":\"CNY\",\"uniqueId\":\"PR202309130024\"},{\"query_1690361668382\":{\"id\":\"326d253f-c28b-4bb5-a54b-b407fbe71f42\",\"serialNo\":\"PR202309130025\"},\"input_1693879193124\":\"LC17\",\"number_1693823979406\":\"1\",\"number_1693823982367\":\"300.00\",\"number_1690362163665\":\"1\",\"number_1690362155400\":\"300.00\",\"number_1690362159095\":\"300.00\",\"number_1692612429157\":null,\"input_1693471244252\":\"31Q0\",\"input_1693471238680\":\"浙江胜道体育用品有限公司\",\"input_1693471241617\":\"31Q0P51000\",\"input_1693471235835\":\"浙江人资行政部\",\"subId\":\"947fa7a7-7b1f-443e-f9fa-bafa648fa293\",\"subIndex\":2,\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"Simon.li 李伟\",\"createdByNo\":\"202106485\",\"createdByTripartiteNo\":\"ou_14fdad93b7caab808559ad4c92a2f128\",\"submitedByNo\":\"202106485\",\"submitedByName\":\"Simon.li 李伟\",\"id\":\"326d253f-c28b-4bb5-a54b-b407fbe71f42\",\"formId\":\"dd548bb2-9cf2-478c-8b7f-828c1492ba7b\",\"definitionId\":\"138dbc3b-e092-44e4-b44c-ddd0c0a095c1\",\"serialNo\":\"PR202309130025\",\"createdBy\":{\"value\":\"202106485\",\"label\":\"Simon.li 李伟\",\"code\":\"202106485\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"E7740D86-3F64-4D65-8344-E2693C0FA8EB\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"input_1689556934951\":\"002\",\"input_1689556940115\":\"31Q0\",\"input_1689556940761\":\"浙江胜道体育用品有限公司\",\"input_1689556941164\":\"31Q0P51000\",\"input_1689556941526\":\"浙江人资行政部\",\"input_1689556941824\":\"SPQ40038\",\"input_1689556942153\":\"上海复御信息科技有限公司\",\"input_1689725618789\":\"LC17\",\"input_1689725620118\":\"白板\",\"input_1693388113761\":\"宜家\",\"input_1693388116253\":\"双面白板\",\"input_1689556942672\":\"白板\",\"number_1689557109961\":\"1\",\"number_1689557128622\":\"300.00\",\"number_1689557130034\":\"300.00\",\"textarea_1689557155464\":\"行政资产测试\",\"number_1689557268505\":\"1\",\"number_1689557269101\":\"300.00\",\"number_1689557269509\":\"1\",\"number_1689557270210\":\"300.00\",\"input_1693038392515\":\"FKPR202309130019\",\"input_1689725521319\":\"208000025\",\"input_1689725515608\":\"金磊\",\"date_1689556928024\":\"2023-09-13 00:00:00\",\"input_1689556933730\":\"CC1431Q02309130004\",\"districtSelect_1694154027560\":{\"label\":\"浙江区部\",\"value\":\"2014\"},\"input_1693470109280\":\"CNY\",\"uniqueId\":\"PR202309130025\"}],\"fileUpload_1692352603480\":[],\"number_1692612874632\":2,\"number_1692612923658\":2,\"number_1691488784203\":\"0\",\"uniqueId\":\"PO202309130017\"},\"input_1692690436278\":\"上海复御信息科技有限公司\",\"input_1692352251937\":\"浙江行政资产采购测试-x\",\"input_1690364031339\":\"PO202309130017\",\"date_1690363705544\":\"2023-09-13 00:00:00\",\"table_1693812976891\":[{\"number_1693812356288\":\"1\",\"number_1693812701913\":\"1000.00\",\"number_1693812706415\":1000,\"number_1693812704399\":\"1\",\"number_1693812361605\":\"1000.00\",\"query_1693813428128\":{\"id\":\"bce67b31-ef1b-4053-abe3-715178690157\",\"serialNo\":\"POS202309130045\"},\"input_1693879289935\":\"GC01\",\"input_1694399512596\":\"双人桌\",\"input_1694399515026\":\"11\",\"subId\":\"4b6f6971-3c72-46dc-9e93-b78bed9892c2\",\"subIndex\":1,\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"金磊\",\"createdByNo\":\"208000025\",\"createdByTripartiteNo\":\"ou_8872fe2ebdf3cdf57e4dc4e90d237d3b\",\"submitedByNo\":\"208000025\",\"submitedByName\":\"金磊\",\"id\":\"bce67b31-ef1b-4053-abe3-715178690157\",\"formId\":\"538b22d2-dd5a-4e56-abbf-57c3bfabd7fa\",\"definitionId\":\"2c2c75b1-f492-417d-b6da-36575dc4c701\",\"serialNo\":\"POS202309130045\",\"createdBy\":{\"value\":\"208000025\",\"label\":\"金磊\",\"code\":\"208000025\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"08F089DA-FA5C-472E-911D-2CAF3716DEA6\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"number_1691549506945\":\"1\",\"number_1693814436665\":\"1000.00\",\"number_1691549512055\":\"1000.00\",\"input_1692325390888\":\"PR202309130024\",\"input_1690515090912\":\"CC1431Q02309130004\",\"input_1690515092182\":\"001\",\"input_1690515208137\":\"办公桌\",\"input_1693879073770\":\"GC01\",\"input_1690515208796\":\"办公桌\",\"input_1693532551982\":\"双人桌\",\"input_1693532554219\":\"11\",\"input_1693471587998\":\"31Q0\",\"input_1693471589352\":\"浙江胜道体育用品有限公司\",\"input_1693471590188\":\"31Q0P51000\",\"input_1693471592536\":\"浙江人资行政部\",\"number_1690515242723\":\"1\",\"number_1690515246414\":\"1000.00\",\"number_1690515265481\":\"1000.00\",\"number_1691549637623\":\"1\",\"number_1691549645732\":\"1000.00\",\"input_1690515306283\":\"PO202309130017\",\"districtSelect_1693534923228\":{\"value\":\"2014\",\"label\":\"浙江区部\"},\"input_1690514911192\":\"SPQ40038\",\"input_1690514912270\":\"上海复御信息科技有限公司\",\"date_1690514971342\":\"2023-09-13 00:00:00\",\"input_1693471581100\":\"CNY\",\"uniqueId\":\"POS202309130045\"},{\"number_1693812356288\":\"1\",\"number_1693812701913\":\"300.00\",\"number_1693812706415\":300,\"number_1693812704399\":\"1\",\"number_1693812361605\":\"300.00\",\"query_1693813428128\":{\"id\":\"d1dca09e-d364-4760-9a3b-c5e73fc41a20\",\"serialNo\":\"POS202309130046\"},\"input_1693879289935\":\"LC17\",\"input_1694399512596\":\"双面白板\",\"input_1694399515026\":\"宜家\",\"subId\":\"e9863fd5-7999-4aea-acc6-6e75e43d28d2\",\"subIndex\":2,\"userType\":0,\"statusName\":\"Submit\",\"createdByName\":\"金磊\",\"createdByNo\":\"208000025\",\"createdByTripartiteNo\":\"ou_8872fe2ebdf3cdf57e4dc4e90d237d3b\",\"submitedByNo\":\"208000025\",\"submitedByName\":\"金磊\",\"id\":\"d1dca09e-d364-4760-9a3b-c5e73fc41a20\",\"formId\":\"538b22d2-dd5a-4e56-abbf-57c3bfabd7fa\",\"definitionId\":\"2c2c75b1-f492-417d-b6da-36575dc4c701\",\"serialNo\":\"POS202309130046\",\"createdBy\":{\"value\":\"208000025\",\"label\":\"金磊\",\"code\":\"208000025\",\"type\":\"userName\"},\"createdTime\":\"2023-09-13\",\"status\":2,\"isDelete\":0,\"submitedBy\":\"08F089DA-FA5C-472E-911D-2CAF3716DEA6\",\"submitedTime\":\"2023-09-13\",\"showFull\":false,\"collActive\":[\"1\"],\"number_1691549506945\":\"1\",\"number_1693814436665\":\"300.00\",\"number_1691549512055\":\"300.00\",\"input_1692325390888\":\"PR202309130025\",\"input_1690515090912\":\"CC1431Q02309130004\",\"input_1690515092182\":\"002\",\"input_1690515208137\":\"白板\",\"input_1693879073770\":\"LC17\",\"input_1690515208796\":\"白板\",\"input_1693532551982\":\"双面白板\",\"input_1693532554219\":\"宜家\",\"input_1693471587998\":\"31Q0\",\"input_1693471589352\":\"浙江胜道体育用品有限公司\",\"input_1693471590188\":\"31Q0P51000\",\"input_1693471592536\":\"浙江人资行政部\",\"number_1690515242723\":\"1\",\"number_1690515246414\":\"300.00\",\"number_1690515265481\":\"300.00\",\"number_1691549637623\":\"1\",\"number_1691549645732\":\"300.00\",\"input_1690515306283\":\"PO202309130017\",\"districtSelect_1693534923228\":{\"value\":\"2014\",\"label\":\"浙江区部\"},\"input_1690514911192\":\"SPQ40038\",\"input_1690514912270\":\"上海复御信息科技有限公司\",\"date_1690514971342\":\"2023-09-13 00:00:00\",\"input_1693471581100\":\"CNY\",\"uniqueId\":\"POS202309130046\"}],\"textarea_1692340598209\":\"\",\"fileUpload_1692340612081\":[],\"number_1693040667297\":\"0\",\"number_1693033906768\":2,\"number_1692770470071\":2,\"version\":\"\",\"operator\":{\"id\":\"08f089da-fa5c-472e-911d-2caf3716dea6\",\"name\":\"金磊\",\"employeeno\":\"208000025\"}}} \r\n";
            var eventHub = MefContainer.GetExport<IEventHub>();
            eventHub.ProcessYideaEvent(new RequestData("", "", "", body.ToString(), ""), _cache);
            return Ok();
        }
#if DEBUG
        [HttpPost]
        [Route("Test")]
        public void Test()
        {
            var involvedCodeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
            var financialCodeField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("财务资产编码"));
            var companyCodeField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司代码"));
            var originalValueField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("资产原值"));
            var lJZJField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("累计折旧"));

            var capitalizationDateField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("本金化日期"));
            var scrapDateField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("报废日期"));

            var centerCodeField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心码"));
            var zJDateField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("折旧开始日"));
            var useYearField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("使用年"));
            var useMonthField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("使用月"));
            var zJCodeField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("折旧码"));

            var assetComapnyField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("公司名称"));
            var assetCenterField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("成本中心名称"));

            var assetAmountField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("资产净值"));
            var periodsNumField = _extendFields.FirstOrDefault(x => x.ObjectType == 0 && x.Name.Equals("已提期数"));

            var companyMasterCodeField = _extendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
            var companyMasterNameField = _extendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

            var centerMasterCodeField = _extendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
            var centerMasterNameField = _extendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");
            var companyNameField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
            var centerNameField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");
            UserDefine userDefine = _setting.First(x => x.Name == "资产主数据");
            var company = _setting.First(x => x.Name == "公司主数据");
            var center = _setting.First(x => x.Name == "成本中心");
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var mysqlClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == "mysqlcache").Value;
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            Asset assetInfo = yideaClient.GetAsset("Z1031905310001");
            JsonObject companyDetail = new JsonObject();
            var companyData = yideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
            {
                FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + "31R0" + "\"}]"
            }).ToList();
            string companyName = "";
            if (companyData.Count > 0)
            {
                companyDetail = JsonNode.Parse(JsonSerializer.Serialize(companyData[0].Data)).AsObject();
                JsonObject companyDataJson = JsonNode.Parse(companyData[0].Data["dataJson"].ToString()).AsObject();
                companyDetail[companyMasterNameField.FieldId] = companyDataJson[companyMasterNameField.FieldId].ToString();
                companyName = companyDataJson[companyMasterNameField.FieldId].ToString();
                companyDetail.Remove("dataJson");
                companyDetail[companyMasterCodeField.FieldId] = "31R0";
            }
            JsonObject centerDetail = new JsonObject();
            var centerData = yideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
            {
                FilterString = "[{\"field\":\"" + centerMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + "SP009820" + "\"}]"
            }).ToList();
            string centerName = "";
            if (centerData.Count > 0)
            {
                centerDetail = JsonNode.Parse(JsonSerializer.Serialize(centerData[0].Data)).AsObject();
                JsonObject centerDataJson = JsonNode.Parse(centerData[0].Data["dataJson"].ToString()).AsObject();
                centerDetail[centerMasterNameField.FieldId] = centerDataJson[centerMasterNameField.FieldId].ToString();
                centerName = centerDataJson[centerMasterNameField.FieldId].ToString();
                centerDetail.Remove("dataJson");
                centerDetail[centerMasterCodeField.FieldId] = "SP009820";
            }
            var datajsonNew = assetInfo.DataJson;

            var index = datajsonNew.IndexOf(involvedCodeField.FieldId);
            var lasetindex = datajsonNew.LastIndexOf(involvedCodeField.FieldId);
            if (index != lasetindex)
            {
                datajsonNew = datajsonNew.Substring(0, index) + datajsonNew.Substring(lasetindex, datajsonNew.Length - lasetindex);
            }
            var dataJson = JsonNode.Parse(datajsonNew)!.AsObject();

            dataJson.SetValue(financialCodeField!, "1030000338");

            dataJson.SetValue(companyCodeField!, "31R0");

            dataJson[lJZJField.FieldId] = "-3504.42";


            dataJson.SetValue(originalValueField!, "3539.82");

            dataJson[capitalizationDateField.FieldId] = "2019-05-01";

            dataJson[scrapDateField.FieldId] = "";
            dataJson.SetValue(centerCodeField!, "SP009820");
            dataJson.SetValue(zJDateField!, "2019-06-01");

            dataJson.SetValue(useYearField!, "003");
            dataJson.SetValue(useMonthField!, "000");
            dataJson.SetValue(zJCodeField!, "Z004");

            dataJson[assetAmountField.FieldId] = (decimal.Parse("3539.82") + decimal.Parse("-3504.42"));
            dataJson[periodsNumField.FieldId] = "36"; //DifferMonth(dataItem.ZJDate);

            dataJson[companyNameField.FieldId] = companyName;
            dataJson[centerNameField.FieldId] = centerName;
            dataJson[assetComapnyField.FieldId] = companyDetail;
            dataJson[assetCenterField.FieldId] = centerDetail;
            assetInfo.DataJson = JsonSerializer.Serialize(dataJson);
            try
            {
                //bool updateAssetFlag = YideaClient.UpdateAsset(assetInfo, assetInfo);
                var resultMsg = "成功";
                if (!string.IsNullOrEmpty(assetInfo.ErrorMessage))
                {

                }



            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量处理资产更新--发生异常");
            }
            //JsonObject updateResult = mysqlClient.GetData(new JsonObject { ["Flag"] = 2 });
            //if (updateResult["assetArray"] != null && updateResult["assetArray"]!.ToString() != "")
            //{
            //    List<AssetMaster> updateData = JsonSerializer.Deserialize<List<AssetMaster>>(updateResult["assetArray"]!.ToString())!;
            //    foreach (var dataItem in updateData)
            //    {

            //        Asset assetInfo = yideaClient.GetAsset(dataItem.BarCode);
            //        _logger.LogInformation("资产主数据更新资产：" + dataItem.BarCode);


            //        if (assetInfo != null && !string.IsNullOrEmpty(assetInfo.DataJson))
            //        {
            //            JsonObject companyDetail = new JsonObject();
            //            var companyData = yideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
            //            {
            //                FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + dataItem.CompanyCode + "\"}]"
            //            }).ToList();
            //            if (companyData.Count > 0)
            //            {
            //                companyDetail = JsonNode.Parse(JsonSerializer.Serialize(companyData[0].Data)).AsObject();
            //                JsonObject companyDataJson = JsonNode.Parse(companyData[0].Data["dataJson"].ToString()).AsObject();
            //                companyDetail[companyMasterNameField.FieldId] = companyDataJson[companyMasterNameField.FieldId].ToString();
            //                companyDetail.Remove("dataJson");
            //                companyDetail[companyMasterCodeField.FieldId] = dataItem.CompanyCode;
            //            }

            //            JsonObject centerDetail = new JsonObject();
            //            var centerData = yideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
            //            {
            //                FilterString = "[{\"field\":\"" + centerMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + dataItem.CenterCode + "\"}]"
            //            }).ToList();
            //            if (centerData.Count > 0)
            //            {
            //                centerDetail = JsonNode.Parse(JsonSerializer.Serialize(centerData[0].Data)).AsObject();
            //                JsonObject centerDataJson = JsonNode.Parse(centerData[0].Data["dataJson"].ToString()).AsObject();
            //                centerDetail[centerMasterNameField.FieldId] = centerDataJson[centerMasterNameField.FieldId].ToString();
            //                centerDetail.Remove("dataJson");
            //                centerDetail[centerMasterCodeField.FieldId] = dataItem.CenterCode;
            //            }
            //            var datajsonNew = assetInfo.DataJson;

            //            var index = datajsonNew.IndexOf(involvedCodeField.FieldId);
            //            var lasetindex= datajsonNew.LastIndexOf(involvedCodeField.FieldId);
            //            if (index != lasetindex) {
            //                datajsonNew = datajsonNew.Substring(0,index)+ datajsonNew.Substring(lasetindex, datajsonNew.Length-lasetindex);
            //            }
            //            var dataJson = JsonNode.Parse(datajsonNew)!.AsObject();

            //            dataJson.SetValue(financialCodeField!, dataItem.FinancialCode);

            //            dataJson.SetValue(companyCodeField!, dataItem.CompanyCode);

            //            dataJson[lJZJField.FieldId] = dataItem.LJZJ;


            //            dataJson.SetValue(originalValueField!, dataItem.OriginalValue);

            //            dataJson[capitalizationDateField.FieldId]= dataItem.CapitalizationDate;

            //            dataJson[scrapDateField.FieldId]=dataItem.ScrapDate;
            //            dataJson.SetValue(centerCodeField!, dataItem.CenterCode);
            //            dataJson.SetValue(zJDateField!, dataItem.ZJDate);

            //            dataJson.SetValue(useYearField!, dataItem.UseYear);
            //            dataJson.SetValue(useMonthField!, dataItem.UseMonth);
            //            dataJson.SetValue(zJCodeField!, dataItem.ZJCode);

            //            dataJson[assetAmountField.FieldId]= (decimal.Parse(dataItem.OriginalValue) + decimal.Parse(dataItem.LJZJ));
            //            dataJson[periodsNumField.FieldId]= DifferMonth(dataItem.ZJDate);

            //            dataJson[assetComapnyField.FieldId] = companyDetail;
            //            dataJson[assetCenterField.FieldId] = centerDetail;
            //            assetInfo.DataJson = JsonSerializer.Serialize(dataJson);
            //            bool updateAssetFlag = yideaClient.UpdateAsset(assetInfo, assetInfo);
            //        }
            //    }
            //}
        }
        private int DifferMonth(string date)
        {
            var predate = DateTime.Parse(date);
            var months = ((DateTime.Now.Year - predate.Year) * 12) + DateTime.Now.Month - predate.Month;
            return months;
        }
        [HttpPost]
        [Route("ExportTest")]
        public void ExportTest()
        {


            var template = Path.Combine(SyncService.Common.Constants.WebRootPath, "Templates", "资产导入模板.xlsx");
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            var target = Path.Combine(SyncService.Common.Constants.WebRootPath, "temp", $"{fileName}进销存统计.xlsx");

            System.IO.File.Copy(template, target);
            FileStream file = new FileStream(target, FileMode.Open, FileAccess.Read);
            var workbook = new XSSFWorkbook(file);
            var sheet = workbook.GetSheet("资产台账");
            int rowIndex = sheet.LastRowNum + 1;

            //foreach (var item in assetExportViewModels)
            //{
            //    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
            //    dataRow.CreateCell(0).SetCellValue("Z101230800008");
            //    dataRow.CreateCell(28).SetCellValue("Z101230800008");
            //    dataRow.CreateCell(29).SetCellValue("Z101230800008");
            //    ++rowIndex;
            //}

            using (var stream = new FileStream(target, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
            }

            string base64 = FileToBase64String.FileToBase64(target);

        }

        [HttpPost]
        [Route("GetLog")]
        public void GetLog()
        {

            JsonObject model = new JsonObject
            {

                ["procInstId"] = "a62de6b1-3591-11ee-85fa-005056b1037e",
                ["billNo"] = "CC0432A02308080001",
                ["sourceSystem"] = "CC",
                ["operateUserId"] = "201615755"


            };

            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var esbClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == "Esb").Value;
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;
            var result = esbClient.GetData(model);
            if (result["code"].ToString() == "000000")
            {
                var approvalList = result["result"]!.AsArray();

                int ObjectType = 48;
                CustomizedFormData flowStateForm = new CustomizedFormData();
                flowStateForm.FormId = Guid.Parse("4f850fda-f7ee-4e40-9f81-0f3f7200e656");
                flowStateForm.WebhookPush = false;
                flowStateForm.SerialNo = "CLN202308080001";
                JsonObject customizedFlowStateData = new JsonObject();
                var logTableField = _extendFields.First(x => x.ObjectType == ObjectType && x.Name == "审批日志");
                var approverField = _extendFields.First(x => x.ObjectType == ObjectType && x.Name == "审批人");
                var suggestionField = _extendFields.First(x => x.ObjectType == ObjectType && x.Name == "审批意见");
                var timeField = _extendFields.First(x => x.ObjectType == ObjectType && x.Name == "审批时间");
                var item = new JsonArray();
                foreach (var approval in approvalList)
                {
                    var suggestion = approval!["suggestion"]!.GetValue<string>();
                    suggestion = HtmlParse.NoHtml(suggestion);
                    item.Add(new JsonObject
                    {
                        [approverField.FieldId] = new JsonObject { ["value"] = approval!["userName"]!.GetValue<string>() },
                        [suggestionField.FieldId] = new JsonObject { ["value"] = suggestion },
                        [timeField.FieldId] = new JsonObject { ["value"] = approval!["createDate"]!.GetValue<string>() },
                    });
                }

                var tableFieldValue = new JsonObject
                {
                    [logTableField.FieldId] = item
                };
                customizedFlowStateData.Add(logTableField.FieldId, tableFieldValue);
                flowStateForm.Data = tableFieldValue;
                var updateTableResponse = yideaClient.UpdateCustomizedFormData(flowStateForm, null);

            }
        }

#endif


        /// <summary>
        /// 验证推送数据是否合法
        /// </summary>
        private bool Validate(string dto, string nonce, string timestamp, string signature)
        {
            _logger.LogInformation("body:" + dto);
            _logger.LogInformation(" nonce:" + nonce);
            _logger.LogInformation("timestamp:" + timestamp);
            _logger.LogInformation("signature:" + signature);
            var yiDeaSecret = _setting.First(x => x.Name == "YiDeaSecret");
            var content = string.Join(":", nonce, dto, yiDeaSecret.Id.ToString(), timestamp);
            var buffer = UTF8Encoding.Default.GetBytes(content);
            var key = UTF8Encoding.Default.GetBytes(yiDeaSecret.Id.ToString());
            var sha1 = new HMACSHA1(key);
            var hash = sha1.ComputeHash(buffer.ToArray());
            return BitConverter.ToString(hash).Replace("-", "").ToLower().Equals(signature.Replace("-", ""));
        }
        /// <summary>
        /// 长摊资产作废
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>

        [HttpPost]
        [Route("ScrapAssetFromSAP")]
        public IActionResult ScrapAssetFromSAP([FromBody] List<SapAssetScrapRequest> body)
        {


            int insertData = body.Count();
            int resultData = 0;
            List<SapAssetScrapRequest> errResultData = new List<SapAssetScrapRequest>();
            List<ScrapAssetResult> processResults = new List<ScrapAssetResult>();
            if (body == null || body.Count == 0)
            {
                _logger.LogInformation("接收到来自SAP的长摊资产作废，数据为空");
                return BadRequest("数据不能为空");
            }
            _logger.LogInformation($"接收到来自SAP的资产报废 ScrapAssetFromSAP  body:{JsonSerializer.Serialize(body)}");
            IEnumerable<Lazy<IExchangeClient, Dictionary<string, object>>>? clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var mysqlClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == "mysqlcache").Value;
            foreach (var item in body)
            {
                // 验证每个item的BarCode是否为空或null
                if (string.IsNullOrEmpty(item.BarCode) || item.BarCode == null)
                {
                    processResults.Add(new ScrapAssetResult
                    {
                        Code = 400,
                        Success = false,
                        ErrorMessage = "Error:BarCode 资产编码不能为空", // 错误信息
                        Data = item // 原始数据
                    });
                    _logger.LogInformation($"处理失败：{item.BarCode}，原因：资产编码不能为空, data：{JsonSerializer.Serialize(item)}");
                    continue; // 跳过当前循环，继续处理下一个item
                }
                var jsonObject = new JsonObject();
                jsonObject.Add("FinancialCode", item.FinancialCode);
                jsonObject.Add("CompanyCode", item.CompanyCode);
                jsonObject.Add("OriginalValue", item.OriginalValue);
                jsonObject.Add("LJZJ", item.LJZJ);
                jsonObject.Add("CapitalizationDate", item.CapitalizationDate);
                jsonObject.Add("ScrapDate", item.ScrapDate);
                jsonObject.Add("CenterCode", item.CenterCode);
                jsonObject.Add("ZJDate", item.ZJDate);
                jsonObject.Add("UseYear", item.UseYear);
                jsonObject.Add("UseMonth", item.UseMonth);
                jsonObject.Add("ZJCode", item.ZJCode);
                jsonObject.Add("BarCode", item.BarCode);
                jsonObject.Add("ZSFZCSHQX", item.ZSFZCSHQX);
                jsonObject.Add("ZTSWC", item.ZTSWC);
                jsonObject.Add("BatchId", item.BatchId);
                jsonObject.Add("BatchTotal", item.BatchTotal);
                var query = mysqlClient.SendNotifications(jsonObject);

                try
                {
                    //----------验证是否入库成功----------

                    //记录入库失败
                    if (query["chechklist"]!.GetValue<bool>() == false)
                    {
                        // 失败：记录item、原因（从query的Message中获取）、错误码
                        processResults.Add(new ScrapAssetResult
                        {
                            Code = 400,
                            Success = false,
                            ErrorMessage = query["Message"]?.ToString() ?? "未知错误",
                            Data = item,

                        });
                        _logger.LogInformation($"处理失败：{item.BarCode}，原因：{query["Message"]?.ToString() ?? "未知错误"},data：{JsonSerializer.Serialize(item)}");
                    }

                    //记录入库成功
                    if (query["chechklist"]!.GetValue<bool>() == true)
                    {
                        // 成功：记录成功状态
                        processResults.Add(new ScrapAssetResult
                        {
                            Code = 200,
                            Success = true,
                            ErrorMessage = "处理成功",
                            Data = item,

                        });
                        resultData++;
                        _logger.LogInformation($"{query["Message"]!.ToString()}:{item.BarCode} \n data：{JsonSerializer.Serialize(item)}");
                    }
                }
                catch (Exception ex)
                {

                    // 捕获SendNotifications抛出的异常（如SQL执行错误）
                    processResults.Add(new ScrapAssetResult
                    {
                        Code = 500,
                        Success = false,
                        ErrorMessage = $"系统异常：{ex.Message}", // 记录异常原因
                        Data = item,

                    });
                    _logger.LogError(ex, $"处理{item.BarCode}时发生异常");
                }



            }
            #region 统计成功/失败数量
            int successCount = processResults.Count(r => r.Success);
            int failCount = processResults.Count - successCount;
            var failItems = processResults.Where(r => !r.Success).ToList();
            #endregion
            #region 全部失败或部分失败时，返回错误信息
            if (successCount == 0)
            {
                // 全部失败：说明每个item的失败原因
                return Ok(new
                {
                    code = 400,
                    message = $"SAP传输资产报废数据入库全部失败（共{failCount}条）",
                    errorData = failItems.Select(r => new
                    {
                        ErrorCode = r.Code, // 错误码
                        Reason = r.ErrorMessage, // 具体原因（如“资产编码重复”）
                        Data = r.Data, // 原始数据
                    }).ToList()
                });
            }

            if (failCount > 0)
            {
                // 部分失败：区分每个失败item的原因
                return Ok(new
                {
                    code = 400,
                    message = $"SAP传输资产报废数据部分失败（成功{successCount}条，失败{failCount}条）",
                    errorData = failItems.Select(r => new
                    {
                        ErrorCode = r.Code,
                        Reason = r.ErrorMessage,
                        Data = r.Data,

                    }).ToList()
                });
            }
            #endregion


            //全部成功：返回成功信息
            var successJson = new
            {
                code = 200,
                message = $"SAP传输资产报废数据入库成功,共计{successCount}条",
                data = body
            };
            return Ok(successJson);

        }
        /// <summary>
        /// 店铺在用资产查询接口
        /// </summary>
        /// <param name="activeAsset"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost]
        [Route("ActiveAssetQuery")]
        public ActionResult<object> ActiveAssetQuery([FromBody] ActiveAssetResponse activeAsset)
        {
            #region 业务逻辑
            //店铺在用资产查询接口
            //入参：店铺代码，资产类型（1 = 资讯资产,2 = 行政资产，行政长摊,3 = 工程长摊）
            //出参：在用资产数量，在用资产明细数组（资产编号，资产名称）
            //查询逻辑：
            //1）资产类型为 1,2 时，查询店铺代码为传入店铺代码开头的，所有状态为 在用，借用，占用的 指定类型的资产数量和明细。
            //2）资产类型为 3时，查询成本中心为传入店铺代码开头的，所有状态为 在用，借用，占用的 指定类型的资产数量和明细。
            #endregion
            var AssetBigTypeField = _extendFields.First(x => x.ObjectType == 0 && x.Name == "资产大类");
            var cbzxFormId = _setting.First(x => x.Name == "成本中心");
            var cbzxField = _extendFields.Where(e => e.Name == "成本中心" && e.ObjectType == 52).FirstOrDefault();
            var storeCodeFiled = _extendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            var clients = MefContainer.GetExports<Lazy<IExchangeClient, Dictionary<string, object>>>();
            var yideaClient = clients.First(x => x.Metadata![YdConstants.ID].ToString() == YdConstants.YIDEA).Value;

            //非空判断
            if (activeAsset == null)
            {
                return new customRequest
                {
                    Success = false,
                    Count = 0,
                    Message = "参数不能为空",
                    Data = new List<ActiveAssetRequest>(),
                };
            }
            if (string.IsNullOrWhiteSpace(activeAsset.StoreCode))
            {
                return new customRequest
                {
                    Success = false,
                    Count = 0,
                    Message = "店铺代码不能为空",
                    Data = new List<ActiveAssetRequest>(),
                };
            }
            if (activeAsset.AssetType < 1 || activeAsset.AssetType > 3)

            {
                return new customRequest
                {
                    Success = false,
                    Count = 0,
                    Message = "资产类型参数错误",
                    Data = new List<ActiveAssetRequest>(),
                };
            }

            _logger.LogInformation($"接收到来自SAP的在用资产查询请求 ActiveAssetQuery  body:{JsonSerializer.Serialize(activeAsset)}");

            #region 查询成本中心获取模糊后的店铺名称和店铺代码
            var shopInfo = GetShopInfo(yideaClient, cbzxFormId, cbzxField!, activeAsset.StoreCode);
            if (shopInfo == null)
            {
                return new customRequest
                {
                    Success = false,
                    Count = 0,
                    Message = "店铺信息不存在",
                    Data = new List<ActiveAssetRequest>(),
                };
            }

            #endregion


            // 获取符合条件的资产
            var assets = GetQualifiedAssets(yideaClient, shopInfo);
            if (assets.Count == 0 || assets == null)
            {
                return new customRequest
                {
                    Success = false,
                    Count = 0,
                    Message = "未获取到符合条件的资产",
                    Data = new List<ActiveAssetRequest>(),
                };
            }

            var assetlist = new List<Asset>();
            if (activeAsset.AssetType == 1)
            {
                foreach (var item in assets)
                {
                    var ss = JsonSerializer.Deserialize<JsonObject>(item.DataJson);
                    if (ss[AssetBigTypeField.FieldId]["label"].ToString() == "资讯类资产")
                    {
                        assetlist.Add(item);
                    }

                }
            }
            else if (activeAsset.AssetType == 2)
            {
                foreach (var item in assets)
                {
                    var ss = JsonSerializer.Deserialize<JsonObject>(item.DataJson);
                    if (ss[AssetBigTypeField.FieldId]["label"].ToString() == "行政类资产"
                        || ss[AssetBigTypeField.FieldId]["label"].ToString() == "行政类长摊")
                    {
                        assetlist.Add(item);
                    }

                }
            }
            else if (activeAsset.AssetType == 3)
            {
                foreach (var item in assets)
                {
                    var ss = JsonSerializer.Deserialize<JsonObject>(item.DataJson);
                    if (ss[AssetBigTypeField.FieldId]["label"].ToString() == "工程类长摊")
                    {
                        assetlist.Add(item);
                    }

                }
            }
            else
            {
                throw new Exception("资产大类无法识别");
            }
            List<ActiveAssetRequest> activeAssetRequests = new List<ActiveAssetRequest>();
            activeAssetRequests = assetlist.Select(s => new ActiveAssetRequest
            {
                BarCode = s.Barcode,
                AssetName = s.Name
            }).ToList();



            return new customRequest
            {
                Success = true,
                Count = activeAssetRequests.Count,
                Message = "获取在用资产成功",
                Data = activeAssetRequests,
            };



        }

        /// <summary>
        /// 查询店铺信息
        /// </summary>
        private Dictionary<string, object> GetShopInfo(IExchangeClient client, UserDefine formId, ExtendField field, string storeCode)
        {

            var condition = new JsonArray {
              new JsonObject{

            ["field"] = field.FieldId,
            ["type"] = "input",
            ["label"] = "成本中心",
            ["opt"] = "Equal",
            ["val"] = storeCode
              }
            };

            var queryParam = new QueryParam
            {
                FilterString = JsonSerializer.Serialize(condition)
            };

            var shopData = client.GetCustomizedFormDatas(formId.Id, queryParam).FirstOrDefault();
            if (shopData == null)
            {
                return null;
            }
            var dataJson = JsonSerializer.Deserialize<Dictionary<string, object>>(shopData.Data["dataJson"]!.ToString());
            return new Dictionary<string, object>
            {
                ["id"] = shopData.Id,
                ["storeCode"] = dataJson[field.FieldId].ToString()
            };
        }
        /// <summary>
        /// 获取符合状态条件的资产
        /// </summary>
        private List<Asset> GetQualifiedAssets(IExchangeClient client, Dictionary<string, object> shopInfo)
        {
            var storeCodeFiled = _extendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
            QueryParam queryParam = new QueryParam();

            queryParam.FilterString = "extensionFilters=[{label:\"" + storeCodeFiled!.FieldId + "\",operator:\"Contains\",value:{value:\"" + shopInfo["id"].ToString() + "\",label:\"" + shopInfo["storeCode"].ToString() + "\"}}]";

            return client.GetAssets(queryParam).Where(s => s.State == 1 | s.State == 3 || s.State == 6 || s.IncludedInBill > 0).ToList();

        }
    }
}
